# Create your views here.
from django.http import JsonResponse
from django.contrib import messages
from KeHu.models import KeHu
from ChanPin.models import Chanpin,ChanpinLeibie
from django.forms.models import model_to_dict  # 需要导入这个函数



def ajax_get_kehu_data(request):
    current_user = request.user
    print("current_user:", current_user)
    headers = request.headers
    print("headers:", headers)
    XRequestedWith=request.headers.get('X-Requested-With')
    print("request.headers", request.headers.get('X-Requested-With'))
    if XRequestedWith == 'XMLHttpRequest':
        key = request.GET.get('key')
        print("key", key)
        # 从数据库中获取客户数据
        if key == 'dingdan':
            if current_user.is_superuser:
                data = KeHu.objects.filter(if_gonghai=0, dingdan__isnull=False).order_by('-addtime').values()
            else:
                data = KeHu.objects.filter(admin_user=current_user, if_gonghai=0, dingdan__isnull=False).order_by(
                    '-addtime').values()
        else:
            pass
        print("customer_list数据:", f'{list(data)}')
        customer_list = list(data)
        # 返回 JSON 响应
        return JsonResponse(customer_list, safe=False)  # safe=False 允许非字典对象作为响应
    else:
        # 如果不是 AJAX 请求，可以返回一个错误响应或重定向到其他页面
        return JsonResponse({'error': 'qingqiu chucuo '}, status=400)


from rest_framework import serializers
from ChanPin.models import Chanpin, ChanpinLeibie, Chanpin_gys  # 假设Leibie和Gys是外键关联的模型


class LeibieSerializer(serializers.ModelSerializer):
    class Meta:
        model = ChanpinLeibie
        fields = ['id', 'name' ]  # 替换为Leibie模型中的实际字段名


class GysSerializer(serializers.ModelSerializer):
    class Meta:
        model = Chanpin_gys
        fields = ['id', 'name']  # 替换为Gys模型中的实际字段名


class ChanpinSerializer(serializers.ModelSerializer):
    leibie = LeibieSerializer()  # 嵌套序列化Leibie对象
    gys = GysSerializer()  # 嵌套序列化Gys对象

    class Meta:
        model = Chanpin
        fields = ['id', 'title', 'jiage', 'jiage_dijia', 'leibie', 'gys', 'beizhu', 'fujian', 'cbj']


def get_fenlei_chanpin(request):
    ChanpinLeibie_xz = request.GET.get('ChanpinLeibie_xz')
    XRequestedWith = request.headers.get('X-Requested-With')
    if XRequestedWith == 'XMLHttpRequest':
        data = Chanpin.objects.filter(leibie_id=ChanpinLeibie_xz).select_related('leibie', 'gys')
        serializer = ChanpinSerializer(data, many=True)
        messages.success(request, '获取成功')
        return JsonResponse(serializer.data, safe=False)
    else:
        messages.error(request, '请求错误')
        return JsonResponse({'error': '请求错误'}, status=400)

